<?php

namespace App\Http\Controllers\Common\EntityData\Channel;

use App\Http\Controllers\Controller;
use App\Http\Requests\Common\EntityData\Channel\SpRequest;
use App\Models\Common\EntityData\Channel\Sgroup;
use App\Models\Common\EntityData\Channel\Sp;
use App\Repositories\Common\EntityData\Channel\SpRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;
use DB;
use Validator;

class SpController extends Controller
{
    use ModelForm;

    /** @var  SpRepository */
    private $spRepository;

    public function __construct(SpRepository $spRepo)
    {
        $this->spRepository = $spRepo;
    }

    /**
     * Display a listing of the Sp.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.entity_data.channel.sps.index_header'));
            $content->description(__('common.entity_data.channel.sps.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * Show the form for creating a new Sp.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('common.entity_data.channel.sps.create_header'));
            $content->description(__('common.entity_data.channel.sps.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Sp in storage.
     *
     * @param SpRequest $request
     *
     * @return Response
     */
    public function store(SpRequest $request)
    {
        $input = $request->all();
        $image = $request->file('logo'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.sp');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath      = $rootDir . '/' . $dir . '/' . $newImageName;
                $input['logo'] = $fullPath;
                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }

        $sp = $this->spRepository->create($input);

        Flash::success(__('common.entity_data.channel.sps.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.entity_data.channel.sps.index'));

    }

    /**
     * Display the specified Sp.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $sp = $this->spRepository->findWithoutFail($id);

        if (empty($sp)) {
            Flash::error(__('common.entity_data.channel.sps.not_found'));

            return redirect(route('common.entity_data.channel.sps.index'));
        }

        return view('common.entity_data.channel.sps.show')->with('sp', $sp);

    }

    /**
     * Show the form for editing the specified Sp.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('common.entity_data.channel.sps.edit_header'));
            $content->description(__('common.entity_data.channel.sps.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Sp in storage.
     *
     * @param  int              $id
     * @param SpRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {

        $sp = $this->spRepository->findWithoutFail($id);

        if (empty($sp)) {
            Flash::error(__('common.entity_data.channel.sps.not_found'));

            return redirect(route('common.entity_data.channel.sps.index'));
        }
        $input = $request->all();
        // 如果删除原图
        if (array_key_exists('_file_del_', $input)) {
            $imgUrl       = $sp->logo;
            $uploadConfig = config('custom.base.upload.sp');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $rootDir      = config('filesystems.disks.' . $driver . '.upload');
            if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                $sp->logo = null;
                $sp->save();
            }
            return response()->json(['message' => '删除成功', 'status' => true]);
        }

        $sValidators = [
            'name' => 'required|max:100',
        ];

        $validators = [];

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }

        // 定义校验, 没有移到request
        $validator = Validator::make($request->all(), $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            // 'name'       => '名称',
        ]);

        if ($validator) {
            // 校验
            if ($validator->fails()) {
                return back()->withErrors($validator)->withInput();
            }
        }
        $image = $request->file('logo'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.sp');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath      = $rootDir . '/' . $dir . '/' . $newImageName;
                $input['logo'] = $fullPath;
                $flag          = Storage::disk($driver)->delete($sp->logo);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        $sp = $this->spRepository->update($input, $id);

        Flash::success(__('common.entity_data.channel.sps.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('common.entity_data.channel.sps.index'));
    }

    /**
     * Remove the specified Sp from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->spRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('common.entity_data.channel.sps.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $sp = $this->spRepository->findWithoutFail($id);

        if (empty($sp)) {
            Flash::error(__('common.entity_data.channel.sps.not_found'));

            return redirect(route('common.entity_data.channel.sps.index'));
        }

        if ($flag = $this->spRepository->delete($id)) {

            return response()->json(['message' => __('common.entity_data.channel.sps.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Sp::class, function (Form $form) {

            $form->display('id', 'ID');
            $sgroups = Sgroup::pluck('name', 'id')->toArray();
            $form->select('sgroup_id', 'sp所属组织')->options(['' => '选择'] + $sgroups);
            $form->text('name', '名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->text('sp_no', '服务商编号');
            $form->text('sp_key', '服务商key');
            $form->text('short_desc', '简述')->help('必填');
            $form->image('logo', 'logo')->removable();
            $form->textarea('description', '描述');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Sp::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // //添加按钮
            // if (!\Gate::check('common.entity_data.channel.sps.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     //编辑按钮
            //     if (!\Gate::check('common.entity_data.channel.sps.edit')) {
            //         $actions->disableEdit();
            //     }
            //     //删除按钮
            //     if (!\Gate::check('common.entity_data.channel.sps.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // //导出按钮
            // if (!\Gate::check('common.entity_data.channel.sps.export')) {
            //     $grid->disableExport();
            // }

            // //批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         //批量删除按钮
            //         if (!\Gate::check('common.entity_data.channel.sps.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            //添加按钮
            if (Admin::user()->cannot('common.entity_data.channel.sps.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                //编辑按钮
                if (Admin::user()->cannot('common.entity_data.channel.sps.edit')) {
                    $actions->disableEdit();
                }
                //删除按钮
                if (Admin::user()->cannot('common.entity_data.channel.sps.destroy')) {
                    $actions->disableDelete();
                }
            });

            //导出按钮
            if (Admin::user()->cannot('common.entity_data.channel.sps.export')) {
                $grid->disableExport();
            }

            //批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    //批量删除按钮
                    if (Admin::user()->cannot('common.entity_data.channel.sps.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('sgroup.name', '组织显示名称')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('sp_no', '服务商编号')->sortable();
            $grid->column('sp_key', '服务商key')->sortable();
            $grid->column('short_desc', '简述')->sortable();
            $uploadConfig = config('custom.base.upload.sp');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            $grid->column('logo', 'logo')->image($host);

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
            });
        });
    }
}
